package com.liu.yuoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.yuoj.common.ErrorCode;
import com.liu.yuoj.constant.CommonConstant;
import com.liu.yuoj.exception.BusinessException;
import com.liu.yuoj.exception.ThrowUtils;
import com.liu.yuoj.model.dto.question.QuestionQueryRequest;
import com.liu.yuoj.model.entity.Question;
import com.liu.yuoj.model.entity.User;
import com.liu.yuoj.model.vo.QuestionVO;
import com.liu.yuoj.model.vo.UserVO;
import com.liu.yuoj.service.QuestionService;
import com.liu.yuoj.mapper.QuestionMapper;
import com.liu.yuoj.service.UserService;
import com.liu.yuoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【question(题目表)】的数据库操作Service实现
* @createDate 2025-01-12 21:33:08
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService {

    @Resource
    private UserService userService;

    /**
     * 校验参数
     *
     * @param question
     */
    @Override
    public void valid(Question question, boolean add) {
        if (question == null) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //校验参数
        String title = question.getTitle ();
        String content = question.getContent ();
        String tags = question.getTags ();
        String answer = question.getAnswer ();
        String judgeCase = question.getJudgeCase ();
        String judgeConfig = question.getJudgeConfig ();
        //创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf (StringUtils.isAnyBlank (title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank (title) && title.length () > 80) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank (content) && content.length () > 8192) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (StringUtils.isNotBlank (answer) && answer.length () > 8192) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR, "答案过长");
        }
        if (StringUtils.isNotBlank (judgeCase) && judgeCase.length () > 8192) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR, "判题用例过长");
        }
        if (StringUtils.isNotBlank (judgeConfig) && judgeConfig.length () > 8192) {
            throw new BusinessException (ErrorCode.PARAMS_ERROR, "判题配置过长");
        }
    }

    @Override
    public QuestionVO getQuestionVO(Question question) {
        QuestionVO questionVO = QuestionVO.objToVo (question);
        // 1. 关联查询用户信息
        Long userId = question.getUserId ();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById (userId);
        }
        UserVO userVO = userService.getUserVO (user);
        questionVO.setUserVO (userVO);
        return questionVO;
    }

    @Override
    public Wrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<> ();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }
        Long id = questionQueryRequest.getId ();
        String title = questionQueryRequest.getTitle ();
        String content = questionQueryRequest.getContent ();
        List<String> tags = questionQueryRequest.getTags ();
        String answer = questionQueryRequest.getAnswer ();
        Long userId = questionQueryRequest.getUserId ();
        String sortField = questionQueryRequest.getSortField ();
        String sortOrder = questionQueryRequest.getSortOrder ();

        // 拼接查询条件
        queryWrapper.like (StringUtils.isNotBlank (title), "title", title);
        queryWrapper.like (StringUtils.isNotBlank (content), "content", content);
        queryWrapper.like (StringUtils.isNotBlank (answer), "answer", answer);
        if (CollectionUtils.isNotEmpty (tags)) {
            for (String tag : tags) {
                queryWrapper.like ("tags", "\"" + tag + "\"");
//                queryWrapper.like ("tags",tag);
            }
        }
        queryWrapper.eq (ObjectUtils.isNotEmpty (id), "id", id);
        queryWrapper.eq (ObjectUtils.isNotEmpty (userId), "userId", userId);
        queryWrapper.eq ("isDelete", false);
        queryWrapper.orderBy (SqlUtils.validSortField (sortField), sortOrder.equals (CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage) {
        //获取列表记录
        List<Question> questionList = questionPage.getRecords ();
        //新存放数据Page集合
        Page<QuestionVO> questionVOPage = new Page<> (questionPage.getCurrent (), questionPage.getSize (), questionPage.getTotal ());
        if (CollectionUtils.isEmpty (questionList)) {
            return questionVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionList.stream ().map (Question::getUserId).collect (Collectors.toSet ());  //set集合中的元素是不重复的
        Map<Long, List<User>> userIdUserListMap = userService.listByIds (userIdSet).stream ()  //根据userId来进行分组
                .collect (Collectors.groupingBy (User::getId));
        // 填充信息
        List<QuestionVO> questionVOList = questionList.stream ().map (question -> {
            QuestionVO questionVO = QuestionVO.objToVo (question);
            Long userId = question.getUserId ();
            User user = null;
            if (userIdUserListMap.containsKey (userId)) {
                user = userIdUserListMap.get (userId).get (0);
            }
            questionVO.setUserVO (userService.getUserVO (user));
            return questionVO;
        }).collect (Collectors.toList ());
        questionVOPage.setRecords (questionVOList);
        return questionVOPage;
    }


}





